<?php
include '../config.php';

session_start();

// Connecting, selecting database
$mysqli = new mysqli($MYSQL_HOST, $MYSQL_USERNAME, $MYSQL_PASSWORD, $MYSQL_DB_NAME);
if ($mysqli->connect_errno) {
	echo "ERR";
} else {
	
	$mysqli->set_charset("utf8");

	$query = sprintf($GET_USER_PASSWORD, $_SESSION["id_utente"]);

	$verify = $mysqli->query($query);
	
	if (!$verify) {
		mysqli_free_result($verify);
		$mysqli->close();
		echo "ERR";
	} else {
		if ($verify->num_rows) {
			$user = $verify->fetch_assoc();
			$old_password = $_POST['oldPassword'];
			$hash_old = crypt($old_password, $PSW_SALT);
			for ($i = 0; $i < $HASHING_ITERATIONS; ++$i)
			{
				$hash_old = crypt($hash_old . $old_password, $PSW_SALT);
			}
			if ($user["password"] == $hash_old) {
				$verify->free();
				$new_password = $_POST['newPassword'];
				$hash_new = crypt($new_password, $PSW_SALT);
				for ($i = 0; $i < $HASHING_ITERATIONS; ++$i)
				{
					$hash_new = crypt($hash_new . $new_password, $PSW_SALT);
				}
				$query = sprintf($UPDATE_USER_PASSWORD, $hash_new, $_SESSION["id_utente"]);
				$verify = $mysqli->query($query);
				if (!$verify) {
					$mysqli->close();
					echo "ERR";
				} else {
					mysqli_free_result($verify);
					$mysqli->close();
					echo "OK";
				}
			} else {
				mysqli_free_result($verify);
				$mysqli->close();
				echo "KO";
			}
		} else {
			mysqli_free_result($verify);
			$mysqli->close();
			echo "ERR";
		}
	}
}
?>
